import { createRouter, createWebHistory } from 'vue-router'
import { showToast } from 'vant';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'lauout',
      component: () => import('@/views/layout/indexView.vue'),
      redirect: '/home', // 重定向
      children: [
        {
          path: '/home',
          name: 'home',
          component: () => import('@/views/home/indexView.vue')
        },
        {
          path: '/classfily',
          name: 'classfily',
          component: () => import('@/views/classfily/indexView.vue')
        },
        {
          path: '/cart',
          name: 'cart',
          component: () => import('@/views/cart/indexView.vue')
        },
        {
          path: '/mine',
          name: 'mine',
          component: () => import('@/views/mine/indexView.vue')
        },
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/indexView.vue')
    },
    {
      path: '/search',
      name: 'search',
      component: () => import('@/views/search/indexView.vue')
    },
    {
      path: '/detail',
      name: 'detail',
      component: () => import('@/views/detail/indexView.vue')
    },
    {
      path: '/order',
      name: 'order',
      component: () => import('@/views/order/indexView.vue')
    },
    {
      path: '/address',
      name: 'address',
      component: () => import('@/views/address/indexView.vue')
    },
    {
      path: '/404',
      name: '404',
      component: () => import('@/views/404/indexView.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404'
    }
  ]
})

// 全局路由守卫
router.beforeEach((to, from, next)=>{
  // 通过本地存储的token进行验证判断
  // 如果有token，并且已经登陆成功，就可以跳转每一个页面
  // 如果没有token，就表示没有登录，就强制跳转登录页
  // 获取本地存储token
  const token = localStorage.getItem('token')
  if(!token){
    // 验证当前页面的路径是不是/login
    // 本地存储没有token，但是当前页面是在登录页，就直接进行登录就ok了
    if(to.path === '/login'){
      next()
    } else {
      // 本地存储没有token并且当前页面不是在登录页，就提示并且强制跳转登录页
      showToast('请重新登录');
      next('/login')
    }
  } else {
    // 本地有token，路径在登录页，就跳转首页
    if(to.path === 'loign'){
      next('/')
    }
  }

  next()
})

export default router
